package custcare

import (
	uuid "github.com/satori/go.uuid"
	"wave-admin/global"
	"wave-admin/model/custcare"
	"wave-admin/model/custcare/request"
	"wave-admin/model/custcare/response"
	"wave-admin/model/system"
	SystemReq "wave-admin/model/system/request"
	"wave-admin/utils"
)

type SysUserService struct{}

func (sysUserService *SysUserService) UpdateSysUser(req request.UpdateSysUser, id int) (err error) {
	var user system.SysUser
	err = global.GnDb.First(&user, id).Error
	if err != nil {
		return err
	}

	var visitor custcare.CusVisitor
	err = global.GnDb.Model(&custcare.CusVisitor{}).Where("admin_id = ?", id).First(&visitor).Error

	if visitor.ID > 0 {
		var status uint8
		status = 2
		if req.IsService {
			status = 1
		}
		update := custcare.CusVisitor{
			Status:   status,
			Nickname: user.Nickname,
			Avatar:   utils.TransformImageUrl(user.Avatar),
		}
		err = global.GnDb.Model(&custcare.CusVisitor{}).Where("admin_id = ?", id).Updates(update).Error
	} else {
		add := custcare.CusVisitor{
			UUID:     uuid.NewV4(),
			AdminId:  user.ID,
			Nickname: user.Nickname,
			Avatar:   utils.TransformImageUrl(user.Avatar),
		}
		err = global.GnDb.Create(&add).Error
	}

	return err
}

func (sysUserService *SysUserService) UpdateAvatar(id uint64) (err error) {
	var user system.SysUser
	err = global.GnDb.First(&user, id).Error
	if err != nil {
		return err
	}
	avatar := utils.TransformImageUrl(user.Avatar)

	var visitor custcare.CusVisitor
	err = global.GnDb.Model(&custcare.CusVisitor{}).Where("admin_id = ?", user.ID).First(&visitor).Error
	if err != nil {
		return err
	}
	if avatar != visitor.Avatar {
		update := custcare.CusVisitor{
			Nickname: user.Nickname,
			Avatar:   avatar,
		}
		err = global.GnDb.Model(&custcare.CusVisitor{}).Where("admin_id = ?", id).Updates(update).Error
	}

	return err
}

func (sysUserService *SysUserService) GetUserList(info SystemReq.UserList) (err error, list interface{}, total int64) {
	if info.Status == "" {
		info.Status = "1"
	}

	limit := info.PageSize
	offset := info.PageSize * (info.CurrentPage - 1)
	db := global.GnDb.Model(&system.SysUser{}).Where("status = ?", info.Status)
	var userList []system.SysUser
	if info.Username != "" {
		db = db.Where("username LIKE ?", "%"+info.Username+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return err, userList, total
	}

	err = db.Limit(limit).Offset(offset).Find(&userList).Error

	var pageList []response.UserInfo
	for _, user := range userList {
		var visitor custcare.CusVisitor
		global.GnDb.Model(&custcare.CusVisitor{}).Where("admin_id = ?", user.ID).First(&visitor)
		isService := false
		if visitor.ID > 0 && visitor.Status == 1 {
			isService = true
		}
		u := response.UserInfo{
			Id:        user.ID,
			UUID:      user.UUID,
			Username:  user.Username,
			Nickname:  user.Nickname,
			Avatar:    utils.TransformImageUrl(user.Avatar),
			Status:    user.Status,
			IsService: isService,
		}
		pageList = append(pageList, u)
	}

	return err, pageList, total
}
